<template>
  <div class="AddOrUpdate_main add_container column_three">
    <div class="main_main">
      <el-form ref="form" :model="formData" :rules="rules" :inline="true">
        <el-form-item label="其他出库单号" prop="formCode">
          <CodeRuleInput :band-value.sync="formData.formCode" table-name="wms_other_out_form" column-name="form_code" :is-edit="id" />
        </el-form-item>
        <el-form-item label="出库人员" prop="outByName">
          <el-input v-model="formData.outByName" placeholder="暂无" disabled />
        </el-form-item>
        <el-form-item label="出库时间" prop="outTime">
          <el-date-picker
            v-model="formData.outTime"
            type="datetime"
            value-format="yyyy-MM-dd HH:mm:ss"
            format="yyyy-MM-dd HH:mm:ss"
            placeholder="请选择"
            :editable="false"
          />
        </el-form-item>
        <el-form-item label="出库类型" prop="formTypeId">
          <DictSelect
            :band-value.sync="formData.formTypeId"
            dict-type="outWarehouse"
          />
        </el-form-item>
        <el-form-item label="关联单据" class="clickChoose" prop="materialCode">
          <el-input v-model="formData.bindFormCode" placeholder="请输入" />
        </el-form-item>
        <el-form-item label="附件" class="double">
          <FileManageFull
            :file-names="formData.fileName"
            :file-real-names="formData.fileRealName"
            :file-urls="formData.fileUrl"
            :row-index="1"
            @fileName="setFileName"
          />
        </el-form-item>
        <el-form-item label="备注" class="double">
          <el-input
            v-model="formData.remark"
            maxlength="200"
            show-word-limit
            type="textarea"
            placeholder="请输入"
          />
        </el-form-item>
      </el-form>
      <div class="formItem_header">
        <div class="formItem_header_setting">出库明细<svg-icon icon-class="页面配置" @click.native="secondPageSetting" />
        </div>
        <div class="formItem_header_operate">
          <a class="formItem_header_operate_item" @click="add">
            <svg-icon icon-class="新增" />
            <div class="item_name">添加</div>
          </a>
          <!-- <a class="formItem_header_operate_item" @click="importSpareParts">
            <svg-icon icon-class="导入" />
            <div class="item_name">导入</div>
          </a> -->
          <a class="formItem_header_operate_item delete" @click="remove1">
            <svg-icon icon-class="删除" />
            <div class="item_name">删除</div>
          </a>
        </div>
      </div>
      <div ref="table_container2" class="table_container">
        <el-table
          ref="table"
          :data="tableData"
          max-height="400"
          stripe
          border
          :header-cell-class-name="headerCellClassName"
          @selection-change="selectionChange1"
        >
          <el-table-column type="selection" width="70" align="center" />

          <Column
            v-for="(column,index) in tableColumns"
            :key="index"
            :prop="column.prop"
            :is-show="column.isShow"
            :label="column.label"
            :sortable="column.sortable"
            :width="column.width"
            :min-width="column.minWidth"
            :fixed="column.fixed"
            :column-type="column.columnType"
            :is-tree="column.isTree"
          />
          <el-table-column label="出库数量" fixed="right" :min-width="SETTINGS.settings_decimalDigits_length" prop="outStockNumAll">
            <template slot-scope="scope">
              <el-input
                v-if="scope.row.newData.length > 1"
                v-model="scope.row.outStockNumAll"
                readonly
                placeholder="请选择"
                clearable
                @click.native="enterWarehouse(scope.row,scope.$index)"
              />
              <el-input
                v-else
                v-model="scope.row.outStockNumAll"
                placeholder="请输入"
                clearable
              />
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>
    <div class="main_bottom">
      <el-button type="cancel" @click.stop="cancel">取消</el-button>
      <el-button @click.stop="onSave">保存</el-button>
      <el-button @click.stop="onSubmit">提交</el-button>
    </div>
  </div>
</template>

<script>
import { addOrUpdate, getInfo } from '@/api/warehouseManagement/elseOutWarehouse'
import warehouseInventory from '../warehouseInventory/addWarehouseInventory'
import moment from 'moment'
import ImportData from '@/components/JLink/common/ImportData'
import warehouse from './addInventory'
import Big from 'big.js'
export default {
  name: 'AddOrUpdate',
  props: {
    layerid: {},
    id: {},
    defaultValue: {}
  },
  data() {
    return {
      formData: {
        id: undefined,
        code: undefined,
        name: undefined,
        simpleName: undefined,
        categoryCode: undefined,
        belongBysStr: undefined,
        roleIdsArray: undefined,
        roleIds: undefined,
        typeId: undefined,
        model: undefined,
        purchaseTime: undefined,
        userId: undefined,
        protoId: undefined,
        protoName: undefined,
        typeName: undefined,
        realName: undefined,
        outTime: '',
        formTypeId: '',
        fileName: '',
        fileRealName: '',
        fileUrl: '',
        remark: undefined,
        status: 1,
        details: []
      },
      tableHeight: '400',
      isOutWarehouseNum: false,
      tableData: [],
      tableList: [],
      selectionsAll1: [],
      selectionsAll: [], // 表格所有页选中的行
      inx: 1,
      rules: {
        formTypeId: [
          { required: true, message: '出库类型不能为空', trigger: 'change' }
        ],
        formCode: [
          { required: true, message: '其他出库单号不能为空', trigger: 'blur' }
        ]
      },
      tableColumns: [], // 表格实际用的字段
      defaultTableColumns: [// 表格常规字段（初始值）
        { prop: 'materialCode', label: '物料编码', minWidth: '140' },
        { prop: 'materialName', label: '物料名称', minWidth: '140' },
        { prop: 'materialModel', label: '规格型号', minWidth: '100' },
        { prop: 'materialTypeName', label: '物料分类' },
        { prop: 'materialUnitName', label: '物料单位' },
        { prop: 'descriptionName', label: '物料属性', isShow: false },
        { prop: 'materialWeight', label: '重量', isShow: false },
        { prop: 'materialTexture', label: '材质', isShow: false },
        { prop: 'materialBrand', label: '品牌', isShow: false },
        { prop: 'remark', label: '备注', columnType: 'input', minWidth: '140' }
      ]
    }
  },
  created() {
    this.getSecondPageSetting(this, '其他出库单新增或编辑', 'tableColumns', this.defaultTableColumns)

    if (!this.id) { // 没有id就是新增
      this.formData.outByName = this.$store.state.user.name
      this.formData.outBy = this.$store.state.user.userId
      this.formData.outTime = moment(new Date()).format('YYYY-MM-DD HH:mm:ss')
    } else { // 有id就是编辑
      this.getInfo()
    }
  },
  mounted() {
  },
  methods: {
    setFileName(...data) {
      this.$set(this.formData, 'fileName', data[0])
      this.$set(this.formData, 'fileRealName', data[1])
      this.$set(this.formData, 'fileUrl', data[2])
    },
    headerCellClassName(data) {
      if (['outStockNumAll'].indexOf(data.column.property) != -1) {
        return 'column_bt'
      }
    },
    selectionChange1(rows) {
      this.selectionsAll1 = rows
    },
    getInfo() {
      getInfo(this.id).then(res => {
        this.formData = res.data
        this.tableData = res.data.remarks
        if (this.formData.remarks) {
          delete this.formData.remarks
        }
        this.tableData.forEach(item => {
          // if (item.details) {
          //   this.isOutWarehouseNum = true
          // }
          if (item.details && item.details.length > 0) {
            this.isOutWarehouseNum = true
            item.newData = item.details.filter(ele => Number(ele.stockNum) > 0)
          }
        })
        this.formData.roleIdsArray = this.formData.roleIds.split(',')
      })
    },
    remove1() {
      this.selectionsAll1.forEach(item => {
        this.tableData.splice(this.tableData.indexOf(item), 1)
      })
    },
    add() {
      this.$layer.iframe({
        // 弹框
        content: {
          content: warehouseInventory, // 传递的组件对象
          parent: this, // 当前的vue对象
          data: {
            selectedRow: this.tableData
          } // props
        },
        area: ['1320px', '700px'],
        title: '选择物料', // 标题
        shadeClose: false // 点击遮罩是否关闭
      })
    },
    onSubmit() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          if (this.tableData.length <= 0) {
            this.$message.warning('请添加出库明细')
            return
          }
          if (this.tableData.filter(item => !item.outStockNumAll).length > 0) {
            this.$message.warning('出库数量不能为空')
            return
          } else if (this.tableData.filter(item => item.outStockNumAll && !this.SETTINGS.reg_no_zero.test(item.outStockNumAll)).length > 0) {
            this.$message.warning('出库数量未正确填写')
            return
          }
          this.formData.roleIds = this.formData.roleIdsArray
          this.formData.details = this.tableData
          addOrUpdate({ ...this.formData, status: '1' }).then(res => {
            this.$message({
              message: res.msg,
              type: 'success'
            })
            this.$layer.close(this.layerid) // 关闭弹框
            this.$parent.refresh() // 调用父组件的刷新方法
          })
        }
      })
    },
    onSave() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          if (this.tableData.length <= 0) {
            this.$message.warning('请添加出库明细')
            return
          }
          if (this.tableData.filter(item => !item.outStockNumAll).length > 0) {
            this.$message.warning('出库数量不能为空')
            return
          } else if (this.tableData.filter(item => item.outStockNumAll && !this.SETTINGS.reg_no_zero.test(item.outStockNumAll)).length > 0) {
            this.$message.warning('出库数量未填写正确')
            return
          }
          this.formData.roleIds = this.formData.roleIdsArray
          this.formData.details = this.tableData
          addOrUpdate({ ...this.formData, status: '0' }).then(res => {
            this.$message({
              message: res.msg,
              type: 'success'
            })
            this.$layer.close(this.layerid) // 关闭弹框
            this.$parent.refresh() // 调用父组件的刷新方法
          })
        }
      })
    },
    // 选择出库
    enterWarehouse(row, index) {
      this.$layer.iframe({// 弹框
        content: {
          content: warehouse, // 传递的组件对象
          parent: this, // 当前的vue对象
          data: {
            selectedRow: row.details,
            materialId: row.materialId ? row.materialId : '',
            isOutWarehouseNum: this.isOutWarehouseNum ? this.isOutWarehouseNum : ''
          }// props
        },
        area: ['880px', '570px'],
        title: '出库明细', // 标题
        shadeClose: false // 点击遮罩是否关闭
      })
    },
    cancel() {
      this.$layer.close(this.layerid)// 关闭弹框
    },
    // 添加出库明细的回调
    showMaterial(data) {
      console.log(data, 11111111111)
      data.forEach(item => {
        item.otherOutFormId = item.id
        delete item['id']
        if (item.details && item.details.length > 0) {
          item.newData = item.details.filter(ele => Number(ele.stockNum) > 0)
          item.details.forEach(ele => {
            ele.stockDetailsId = ele.id
            delete ele['id']
          })
        }
      })
      this.tableData = this.$deepClone(data)
      if (this.tableData.filter(item => item.details).length > 0) {
        this.isOutWarehouseNum = true
      }
    },
    importSpareParts() { // 导入备件物料
      this.$layer.iframe({// 弹框
        content: {
          content: ImportData, // 传递的组件对象
          parent: this, // 当前的vue对象
          data: {}// props
        },
        area: ['440px', '250px'],
        title: '导入数据', // 标题
        shadeClose: false // 点击遮罩是否关闭
      })
    },
    // 选择出库明细回调
    showWarehouse(row) {
      let num = new Big(0) // 初始化为Big对象0

      const arr = this.$deepClone(this.tableData)
      const rows = this.$deepClone(row)

      rows.forEach(item => {
        if (!item.outStockNum) {
          item.outStockNum = 0
        }
        num = num.plus(new Big(item.outStockNum)) // 正确累加outStockNum

        // 处理stockDetailsId和id
        // if (!this.id) {
        //   item.stockDetailsId = item.id
        //   item.id = ''
        // }
        // else {
        //   arr.forEach(ele => { // 更改为直接forEach而非filter
        //     if (ele.details.length > 0) {
        //       ele.details.forEach(ele2 => {
        //         if (ele2.stockDetailsId == item.id) {
        //           item.stockDetailsId = ele2.stockDetailsId
        //           item.id = ele2.id
        //         }
        //       })
        //     }
        //   })
        // }

        arr.forEach(item2 => {
          if (item.materialId === item2.materialId) {
            item2.outStockNumAll = num.toString()
            // 这里应该是保留原details数组，并非直接替换为row
            item2.details = rows
            // item2.details.push(item)
          }
        })
      })

      this.tableData = arr
    },
    secondPageSetting() { // 二级页面，页面配置
      this.setSecondPageSetting('其他出库单新增或编辑', this.defaultTableColumns)
    }
  }
}
</script>

<style lang="less" scoped>
/deep/ .el-table__body-wrapper {
  padding-bottom: 5px;
}
.formItem_header_setting{
  svg{
    margin-left: 10px;
    font-size: 14px;
    color: #387bfc;
    cursor: pointer;
  }
}
</style>
